package com.jiangxiaofei.citycloud.activity.freshfruits;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.EmptyUtils;
import com.google.gson.Gson;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.bean.GoodIdBean;
import com.jiangxiaofei.citycloud.bean.JsonBean;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.constants.IntConstants;
import com.jiangxiaofei.citycloud.constants.StringConstants;
import com.jiangxiaofei.citycloud.mvp.FreshConstant;
import com.jiangxiaofei.citycloud.mvp.FreshPersenter;
import com.jiangxiaofei.citycloud.param.PutNeedParam;
import com.jiangxiaofei.citycloud.util.GetJsonDataUtil;

import org.json.JSONArray;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * @author: JiangXFei
 * @date: 2017/11/24 0024
 * @content: 果蔬需求发布页面
 */

public class FreshFruitsNeedPublishActivity extends BaseActivity
        implements FreshConstant.PutFreshNeedView {


    private static final int MSG_LOAD_DATA = 0x0005;
    @InjectView(R.id.et_title)
    EditText etTitle;
    @InjectView(R.id.tv_description)
    EditText tvDescription;
    @InjectView(R.id.tv_good_type)
    TextView tvGoodType;
    @InjectView(R.id.linear_select_type)
    LinearLayout linearSelectType;
    @InjectView(R.id.et_good_price)
    EditText etGoodPrice;
    @InjectView(R.id.linear_select_price)
    LinearLayout linearSelectPrice;
    @InjectView(R.id.tv_good_location)
    TextView tvGoodLocation;
    @InjectView(R.id.linear_select_location)
    LinearLayout linearSelectLocation;
    @InjectView(R.id.btn_publish)
    Button btnPublish;

    private int typeId = -1;
    private PutNeedParam putNeedParam = new PutNeedParam();
    private BDLocation bdLocation;

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                default:
                    break;
            }
        }
    };
    private Intent intent;
    private FreshConstant.PutFreshNeedPersenter putFreshNeedPersenter;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_fresh_fruits_need_publish_layout);
        ButterKnife.inject(this);
        mContext = this;
        mActivity = this;
        initTitle();
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        putFreshNeedPersenter = new FreshPersenter(mContext, (FreshConstant.PutFreshNeedView) mActivity);

    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        setLeftOneBg(R.drawable.ic_back_black);
        setCTitle("发布需求");
        mCenterTitle.setTextColor(Color.parseColor("#7b7b7b"));
        rl_layout.setBackgroundColor(Color.parseColor("#ffffff"));
    }

    @Override
    public void setData(Object o) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void message(String str) {

    }

    @Override
    public PutNeedParam PutFreshNeedParam() {
        return putNeedParam;
    }

    @Override
    public void PutNeedSuccess(GoodIdBean idBean) {
        Toast.makeText(mContext, "发布成功", Toast.LENGTH_SHORT).show();
        if (EmptyUtils.isNotEmpty(idBean)) {
            intent = new Intent(mContext, FreshFruitsNeedDetailActivity.class);
            intent.putExtra(StringConstants.FRESHNEEDID, Integer.valueOf(idBean.getId()));
            startActivity(intent);
        }
        mActivity.finish();
    }

    @OnClick({R.id.btn_publish, R.id.linear_select_type, R.id.linear_select_location})
    public void bOnClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btn_publish:
                //发布
                if (isForm()) {
                    //发布商品
                    putFreshNeedPersenter.putFreshhNeed();
                }
                break;
            case R.id.linear_select_type:
                //选择商品类型
                intent = new Intent(mContext, FreshFruitsCassifySelectActivity.class);
                startActivityForResult(intent, IntConstants.FRESHSELECTCASSIFYID);
                break;
            case R.id.linear_select_location:
                //选择产地
                ShowPickerView(tvGoodLocation);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == IntConstants.FRESHSELECTCASSIFYID) {
            typeId = data.getIntExtra(StringConstants.FLEATYPEID, -1);
            String name = data.getStringExtra(StringConstants.FLEATYPE);
            if (EmptyUtils.isNotEmpty(name)) {
                tvGoodType.setText(name);
            }
            if (typeId != -1) {
                putNeedParam.setCat(typeId);
            }
        }
    }

    /**
     * 表单验证
     *
     * @return 表单验证成功返回TRUE
     */
    private boolean isForm() {
        String title = etTitle.getText().toString();
        String description = tvDescription.getText().toString();
        String price = etGoodPrice.getText().toString();
        String location = tvGoodLocation.getText().toString();
        if (EmptyUtils.isEmpty(title)) {
            Toast.makeText(mContext, "请输入需求标题", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (EmptyUtils.isEmpty(description)) {
            Toast.makeText(mContext, "请输入描述信息", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (EmptyUtils.isEmpty(price)) {
            Toast.makeText(mContext, "请输入价格", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (typeId == -1) {
            Toast.makeText(mContext, "请选择分类", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (EmptyUtils.isEmpty(location)) {
            Toast.makeText(mContext, "请输入地址", Toast.LENGTH_SHORT).show();
            return false;
        }
        putNeedParam.setAuthor(Constants.userId);
        putNeedParam.setCat(typeId);
        putNeedParam.setDescription(description);
        if (EmptyUtils.isNotEmpty(Constants.bdLocation)) {
            bdLocation = Constants.bdLocation;
        } else {
            Constants.bdclient.start();
            bdLocation = Constants.bdLocation;
        }
        putNeedParam.setLat(String.valueOf(bdLocation.getLatitude()));
        putNeedParam.setLng(String.valueOf(bdLocation.getLongitude()));
        putNeedParam.setTitle(title);
        putNeedParam.setPrice(price);
        putNeedParam.setProarea(location);
        return true;
    }

    /**
     * 开始加载地址选择器  start
     */
    private void ShowPickerView(final TextView tv) {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(mActivity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);
//                String tx = options2Items.get(options1).get(options2);
                Constants.positions.clear();
                Constants.positions = options3Items.get(options1).get(options2);
                tv.setText(tx);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

//   pvOptions.setPicker(options1Items);//一级选择器
//        pvOptions.setPicker(options1Items, options2Items);//二级选择器
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(mActivity, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);
                        if (Constants.bdLocation != null && CityName.equals(Constants.bdLocation.getCity())) {
                            Constants.positions.add(AreaName);
                        }
                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }


    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
    /**
     * 开始加载地址选择器  end
     */
}
